package com.iepacj.concurrency.ch4.one;

import java.util.concurrent.TimeUnit;

/**
 * Created by iEpac on 16/4/23.
 *
 * 中断状态是线程的一个标志位
 * 而中断操作是线程间一个简便的交互方式
 * 这种交互方式最适合用来取消或者停止任务
 *
 */
public class Shutdown {

    public static void main(String[] args) {

        Runner r = new Runner();

        Thread countThread = new Thread(r, "CountThread");

        countThread.start();

        // 休眠一秒钟 main线程对CountThread进行中断
        // CountThread能够感知中断而结束
        SleepUtils.second(1);
        countThread.interrupt();

        Runner two = new Runner();

        countThread = new Thread(two, "CountThread");

        countThread.start();

        SleepUtils.second(1);

        two.cancle();

    }


    static class Runner implements Runnable {

        private long i = 0;

        private volatile boolean on = true;

        @Override
        public void run() {

            while (on && !Thread.currentThread().isInterrupted()) {
                i++;
            }
            System.out.println("count: " + i);
        }

        public void cancle() {
            on = false;
        }

    }
}
